package com.yuandengta.yomall.order.listener;

import com.rabbitmq.client.Channel;
import com.yuandengta.yomall.order.entity.OrderEntity;
import com.yuandengta.yomall.order.service.AliPayService;
import com.yuandengta.yomall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 定时关单监听器 {@link OrderCloseListener}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@RabbitListener(queues = "order.release.order.queue")
@Slf4j
@Service
public class OrderCloseListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AliPayService aliPayService;

    @RabbitHandler
    public void handlerOrderClose(OrderEntity entity, Message message, Channel channel) {
        log.info("收到过期的订单信息，准备关闭订单，{}", entity);
        try{
            orderService.closeOrder(entity);

            // 手动调用支付宝收单
            aliPayService.close(entity.getOrderSn());

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
